package app.bskkorren.util;

public class SystemUtil
{

	/**
	 * Filters and formats a chain of exception stacktraces according to a given
	 * package filter.
	 * 
	 * @param throwable
	 *            The starting throwable in the exception chain.
	 * @param packageFilter
	 *            The filter that selects the classes that includes the package
	 *            filter in their full names.
	 * @return A string that contains the full chained stacktrace in a readable
	 *         format.
	 */
	public static String formatException(Throwable throwable)
	{
		String FILTER = "app.bskkorren";
		StringBuilder builder = new StringBuilder();
		String lineSep = System.getProperty("line.separator");

		builder.append(lineSep);
		builder.append("  STACKTRACE (paketfilter='" + FILTER + "')" + lineSep);

		while (true) {
			builder.append("  Exception: " + throwable.getClass().getName() + " " + lineSep);
			builder.append(" Meddelande: " + throwable.getMessage() + " " + lineSep);

			StackTraceElement element[] = throwable.getStackTrace();

			for (int i = 0; i < element.length; i++) {
				if (element[i].getClassName().startsWith(FILTER)) {
					builder.append("      at "
							+ element[i].getClassName().replaceAll(FILTER,
									"...") + ":" + element[i].getMethodName()
							+ " line: " + element[i].getLineNumber() + lineSep);
				}
			}
			throwable = throwable.getCause();
			if (throwable == null) break;
		}
		return builder.toString();
	}
}
